package com.auxide.cah;

import java.util.Stack;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.auxide.util.Logger;
import com.auxide.util.NetworkManager;

public class GameActivity extends Activity implements OnClickListener  {

	TextView box;	
	Button[] buttons;
	ProgressDialog dialog;
	
	Stack<String> answers;
	Stack<String> questions;
	
	NetworkManager nm = NetworkManager.getInstance();
	
	Game currentGame;
	
	boolean host;
	String waitingText = "Waiting for answers";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);
		box = (TextView) findViewById(R.id.mainTextbox);

		buttons = new Button[5];

		buttons[0] = (Button) findViewById(R.id.startButton);
		buttons[1] = (Button) findViewById(R.id.cancelButton);
		buttons[2] = (Button) findViewById(R.id.button3);
		buttons[3] = (Button) findViewById(R.id.button4);
		buttons[4] = (Button) findViewById(R.id.button5);

		buttons[0].setOnClickListener(this);
		buttons[1].setOnClickListener(this);
		buttons[2].setOnClickListener(this);
		buttons[3].setOnClickListener(this);
		buttons[4].setOnClickListener(this);

		nm.setIncomingHandler(handler);
		currentGame = Game.getInstance();
		
		host = getIntent().getBooleanExtra("Host", false);
		if(host){
			//I'm the host
			//Decisions:  Only I instantiate the cards, I send them to the clients
			//Need to start and maintain circling queue
			//Every round send new card/cards to client
			//TODO:  questions to have special chars that = place to put answer(s)
			questions = new Stack<String>();
			answers   = new Stack<String>();
			
			CombineLists(getResources().getStringArray(R.array.questions), questions);  
			CombineLists(getResources().getStringArray(R.array.answers1), answers);
			CombineLists(getResources().getStringArray(R.array.answers2), answers);
			CombineLists(getResources().getStringArray(R.array.answers3), answers);
			CombineLists(getResources().getStringArray(R.array.answers4), answers);
			CombineLists(getResources().getStringArray(R.array.answers5), answers);
			CombineLists(getResources().getStringArray(R.array.answers6), answers);
					
		}else{
			//I'm a client
			//Wait for host to send me my cards
			dialog = ProgressDialog.show(this, "", "Loading...", true);
			//Tell host i'm ready
			nm.sendMessage("ClientReady");

			//this should display waiting dialog, until I receive, my cards and the question card
			//also need to build turn queues
		}
		
		
		//Either client or host
		//Need to know if its my turn to choose or not
		//I need to maintain my 5 cards 
		//I need to maintain my score or num of questions won
		
		//if its my turn:
		//I just see the questions, and wait for other player's answers
		
		//if not my turn:
		//I see question, and then send my card(s)
		
		//TODO:  How to end round?  Show chosen answer of course, but also all other answers?
	}


	private void UpdateDisplay(){
		box.setText(currentGame.currentQuestion);
		
		if(currentGame.localPlayer.current){
			//Empty buttons
			for(int i =0; i < buttons.length; i++){
				buttons[i].setText(waitingText);
				buttons[i].setEnabled(false);
			}
		}else{
			//Display your answers
			for(int i =0; i < buttons.length; i++){
				buttons[i].setText(currentGame.getLocalPlayer().getAnswers().get(i));
				buttons[i].setEnabled(true);
			}
		}
	}

	private void CombineLists(String[] a, Stack<String> c){
		for(String s : a){
			c.add(s);
		}
	}

	@Override
	public void onClick(View v) {
		String chosenAnswer = ((Button)v).getText().toString();
		
		if(currentGame.localPlayer.current){
			if(host){
				handleChosenAnswer(chosenAnswer);
			}else{
				nm.sendMessage("ChosenAnswer&" + chosenAnswer);
			}
			//nm.sendMessage("GameVars&" + getJSONMessage(currentQuestion, currentAnswers));
		}else{
			int disabledButtons = 0;
			for(int i = 0; i < buttons.length; i++){
				disabledButtons += buttons[i].isEnabled() ? 0 : 1;
			}
			
			if(disabledButtons < currentGame.answersPerTurn){
				
				nm.sendMessage(getAnswerMessage(chosenAnswer, currentGame.localPlayer));
				((Button)v).setEnabled(false);

			}else{
				for(int i = 0; i < buttons.length; i++){
					buttons[i].setEnabled(false);
				}
			}
		}
	}
	
	void handleChosenAnswer(String chosenAnswer){
		String roundWinner = currentGame.calcScore(chosenAnswer, currentGame.currentQuestion);
		Logger.popUp(roundWinner + " won with " + chosenAnswer);
		currentGame.endRound();
	
		nm.sendMessage("GameVars&" + getStartMessage(currentGame));
	}
	
	

	String getStartMessage(Game g){
		JSONObject message = new JSONObject();
	
		try{
			message.put("Question", g.currentQuestion);
			message.put("Players", g.getPlayersAsJSON());
		}catch(Exception e){
			Logger.e(e);
		}
		return message.toString();
	}
	
	void receivedStartMessage(String json){
		try{
			JSONObject jo = new JSONObject(json);
			currentGame.currentQuestion = jo.getString("Question");
			currentGame.setPlayersFromJSON(jo.getJSONArray("Players"));

			UpdateDisplay();
		}catch(Exception e){
			Logger.e(e);
		}
	}
	
	String getAnswerMessage(String answer, Player p){
		JSONObject jo = new JSONObject();
		try{
			jo.put("Answer", answer);
			jo.put("Player", p.ip);
		}catch(Exception e)
		{
			Logger.e(e);
		}
		return "OfferedAnswer&" + jo.toString();
	}
	
	void receivedAnswer(String msg){
		try{
			JSONObject jo = new JSONObject(msg);
			String answer = jo.getString("Answer");
			String ip = jo.getString("Player");
			
			for(Player p : currentGame.playerList){
				if(p.ip.equals(ip)){
					p.answers.remove(answer);
				}
			}
			
			for(int i =0; i < buttons.length; i++){
				if(!buttons[i].isEnabled()){
					buttons[i].setText(answer);
					buttons[i].setEnabled(true);
					break;
				}
			}
		}catch(Exception e){
			Logger.e(e);
		}
		

	}
	
	public Handler handler = new Handler(new Handler.Callback() {
	    @Override
	    public boolean handleMessage(Message msg) {
	    	if(msg.arg2 == 2){//Message received
	    		try{
	    			String message = (String)msg.obj;
	    			Logger.popUp("Received: " + message);
	    			if(message.equals("ClientReady")){//Host receives this
	    				currentGame.startGame(host,answers, questions);
	    				
	    				String sendToClient = getStartMessage(currentGame);
		    			nm.sendMessage("GameVars&" + sendToClient);
		    			UpdateDisplay();
	    			}
	    			
	    			if(message.startsWith("GameVars")){//Client receives this
		    			if(dialog.isShowing()) dialog.dismiss();		    			
		    			receivedStartMessage(message.split("&")[1]);
	    			}
	    			
	    			if(message.startsWith("OfferedAnswer")){
	    				receivedAnswer(message.split("&")[1]);
	    			}
	    			
	    			if(message.startsWith("ChosenAnswer")){
	    				handleChosenAnswer(message.split("&")[1]);
	    			}
	    		}catch(Exception e){
	    			Logger.e(e);
	    		}
	    	}
			
			return true;
	    }
	});

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}
